import React, {
	PureComponent
} from 'react'
import { connect } from 'dva'
import { Form, Input, Button, Upload } from 'antd'
import Icon from 'react-fa'
import Grid from '@/components/Grid'
import Select from '@/components/Select'
import Dialog, { withRef } from '@/components/Dialog'
import settings, { getPagination } from '@/settings'
import { setType, download, toBytes } from '@/utils'
import { $request } from '@/utils/request'
import Authorized from '@/components/Authorized'

@Form.create()
@connect(({ file: { data } }) => ({ data }))
@withRef
class ModelForm extends React.Component {
	componentDidMount() {
		const {
			id,
			dispatch
		} = this.props;

		if (id) {
			dispatch({
				type: 'file/fetchOne',
				payload: {
					id
				}
			});
		}
	};
	handleSubmit = (_, callback) => {
		const {
			form
		} = this.props

		form.validateFields((err, values) => {
			if (!err) {
				callback(values)
			}
		})
	};
	render() {
		const {
			data = {},
			form: {
				getFieldDecorator
			}
		} = this.props

		return (
			<Form onSubmit={this.handleSubmit} layout="vertical">
	          <Form.Item label="文件名称" {...this.formLayout}>
	            {getFieldDecorator('name', {
					rules: [{
						required: true,
						message: '请输入文件名称'
					}],
	              	initialValue: data.name,
	            })(<Input placeholder="请输入" />)}
	          </Form.Item>
	        </Form>
		)
	}
}

@Form.create()
@connect(({
	app: {
		user = {}
	},
	file: {
		list = {},
		params
	},
	loading
}) => ({
	user,
	list,
	params,
	loading: loading.effects['file/fetchAll'],
}))
class FilePage extends PureComponent {
	state = {
		files: [],
		selectedRows: []
	};
	columns = [{
		title: '文件标题',
		dataIndex: 'name',
		width: 420
	}, {
		title: '文件大小',
		dataIndex: 'size',
		width: 150,
		render: (v, record, index) => {
			return toBytes(v)
		}
	}, {
		title: '上传用户',
		dataIndex: 'cruser',
		width: 120
	}, {
		title: '创建时间',
		dataIndex: 'crtime',
		width: 150,
		align: 'center'
	}];
	componentDidMount() {
		const {
			dispatch,
			match
		} = this.props;
		const {
			params: {
				id
			}
		} = match
		dispatch({
			type: 'file/fetchAll',
			payload: {
				id: Number(id)
			}
		});
	};
	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};
	handleEdit = e => {
		const { selectedRows } = this.state;
		const { id } = selectedRows[0];
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'file/reset'
		});
		Dialog.open({
			title: '文件重命名',
			url: 'file/update',
			data: {
				id
			},
			options: {
				type: 'put'
			},
			onOk: data => {
				this.handleReload()
			},
			component: props => (<ModelForm {...props} id={id} />),
			connect: ({ loading }) => ({ loading: loading.effects['file/fetchOne'] })
		})
	};
	handleRemove = e => {
		const { selectedRows } = this.state;
		Dialog.confirm({
			title: '确认提示',
			content: '确定要删除选中的文件？',
			onOk: () => {
				$request.put('file/delete', {
					data: {
						ids: selectedRows.map(_ => _.id)
					}
				}).then(data => {
					this.handleReload()
				})
			}
		})
	};
	handleGridChange = (oldPagination, sorter) => {
		const { params, dispatch, match } = this.props;
		const {
			params: {
				id
			}
		} = match
		
		const pagination = getPagination(oldPagination)
		const payload = {
			...params,
			...pagination,
			id: Number(id)
		}

		if (sorter.field) {
			payload.sorter = sorter.field
			payload.order = sorter.order
		}

		dispatch({
			type: 'file/fetchAll',
			payload,
		})
	};
	handleReload = () => {
		const { params, dispatch, match } = this.props;
		const {
			params: {
				id
			}
		} = match
		dispatch({
			type: 'file/fetchAll',
			payload: {
				...params,
				id: Number(id)
			}
		})
	};
	// handleSearch = (value, e) => {
	// 	e.preventDefault();
	// 	const { params, dispatch, match } = this.props;
	// 	const {
	// 		params: {
	// 			id
	// 		}
	// 	} = match
	// 	const pagination = getPagination({
	// 		pageNumber: 1
	// 	})
	// 	dispatch({
	// 		type: 'file/fetchAll',
	// 		payload: {
	// 			...params,
	// 			...pagination,
	// 			name: value,
	// 			id: Number(id)
	// 		}
	// 	})
	// };
	handleSubmit = e => {
		e.preventDefault()

		const {
			form
		} = this.props

		form.validateFields((err, values) => {
			const { params, dispatch } = this.props;
			const pagination = getPagination({
				pageNumber: 1
			})
			dispatch({
				type: 'file/fetchAll',
				payload: {
					...params,
					...pagination,
					...values
				}
			})
		})
	};
	renderProcess = () => {
		const {
			files
		} = this.state
		const prefixCls = 'upload-process'

		const renderFiles = files.map((file, index) => {
			return (
				<div className="upload-file" key={index}>
					<img src={file.src} alt="" />
					<span className="file-item file-name"><span className="file-name-inner">{file.name}</span></span>
					{file.status === 'uploading' && <span className="file-item file-progress"><span className="file-progress-bar" style={{width: `${file.percent}%`}}></span></span>}
					{file.status === 'error' && <span className="file-item file-message text-danger"></span>}
					{file.status === 'done' && <span className="file-item file-message">上传完成</span>}
				</div>
			)
		})
		if (files && files.length > 0) {
			return (
				<div className={prefixCls}>
					<div className={`${prefixCls}-header`}>
						<h2>正在上传</h2>
						<div className={`${prefixCls}-toolbar`}>
							<Icon name="remove" onClick={e => this.setState({ files: [] })} />
						</div>
					</div>
					<div className={`${prefixCls}-body`}>
						{renderFiles}
					</div>
				</div>
			)
		} else {
			return null
		}
	};
	handleUploadStart = (file, fileList) => {
		return setType(file)
	};
	handleChange = ({file, fileList, event}) => {
		const done = fileList.every(_ => _.status === 'done')
		if (done) {
			this.handleReload()
		}
		this.setState({
			files: [...fileList]
		})
	};
	handleDonwload = e => {
		// const { dispatch } = this.props
		const { selectedRows } = this.state;
		const { id } = selectedRows[0];

		// dispatch({
		// 	type: 'file/download',
		// 	payload: {
		// 		id
		// 	}
		// })
		download('file/download', {
			id
		})
	};
	render() {
		const { files, selectedRows } = this.state;
		const {
			user: {
				authorities = []
			},
			params,
			form: {
				getFieldDecorator
			},
			loading,
			list: {
				data,
				total
			},
			match
		} = this.props

		const {
			params: {
				id: folderId
			}
		} = match

		const upload = {
				name: 'file',
				className: 'x-upload',
				beforeUpload: this.handleUploadStart,
				showUploadList: false,
				fileList: files,
				onChange: this.handleChange
			}
		const newUpload = {
			...upload,
			multiple: true,
			action: `${settings.base}/file/upload`,
			data: {
				folderId
			}
		}
		const {
			id
		} = selectedRows[0] || {}
		const updateUpload = {
			...upload,
			action: `${settings.base}/file/update`,
			data: {
				id
			}
		}
		const pageNumber = params[settings.pageNumber]
		return (
			<React.Fragment>
				<div className="x-wrap">
					<div className="x-panel">
						<div className="x-toolbar">
							<div className="fl">
								<Button.Group>
									<Authorized authorities={authorities} authority="FILE_ADD"><Upload {...newUpload}><Button type="primary" icon="upload">上传文件</Button></Upload></Authorized>
									<Authorized authorities={authorities} authority="FILE_EDIT"><Button onClick={this.handleEdit} disabled={selectedRows.length !== 1}>重命名</Button></Authorized>
									<Authorized authorities={authorities} authority="FILE_DEL"><Button type="danger" disabled={selectedRows.length === 0} onClick={this.handleRemove}>删除文件</Button></Authorized>
								</Button.Group>
								<Authorized authorities={authorities} authority="FILE_UPLOAD"><Upload {...updateUpload} disabled={selectedRows.length !== 1}><Button icon="upload" disabled={selectedRows.length !== 1}>重新上传</Button></Upload></Authorized>
								<Authorized authorities={authorities} authority="FILE_DOWNLOAD"><Button icon="download" disabled={selectedRows.length !== 1} onClick={this.handleDonwload}>下载</Button></Authorized>
							</div>
							<div className="fr x-query">
								<Form layout="inline" onSubmit={this.handleSubmit}>
									<Form.Item>
							            {getFieldDecorator('name')(
							              <Input placeholder="请输入要查询的文件名称" />
							            )}
						          	</Form.Item>
									<Form.Item>
							            {getFieldDecorator('type')(
							              <Select placeholder="请选择" style={{width: 120}}>
							                	<Select.Option value="">全部类型</Select.Option>
												<Select.Option value="image">图片</Select.Option>
												<Select.Option value="word">Word文档</Select.Option>
												<Select.Option value="excel">Excel文档</Select.Option>
												<Select.Option value="ppt">PPT文档</Select.Option>
												<Select.Option value="pdf">PDF类型</Select.Option>
												<Select.Option value="txt">文本文档</Select.Option>
												<Select.Option value="audio">音频</Select.Option>
												<Select.Option value="video">视频</Select.Option>
												<Select.Option value="zip">压缩包</Select.Option>
												<Select.Option value="code">代码文件</Select.Option>
												<Select.Option value="unknown">其他</Select.Option>
							              </Select>
							            )}
							        </Form.Item>
						          	<Form.Item>
							            <Button type="primary" htmlType="submit">查询</Button>
							        </Form.Item>
								</Form>
							</div>
						</div>
						<div className="x-fixed">
							<Grid 
							selectedRows={selectedRows} 
							onSelectRow={this.handleSelectRows} 
							columns={this.columns} 
							data={data}
							loading={loading}
							pagination={{
								pageNumber,
								total
							}}
							onReload={this.handleReload}
							onChange={this.handleGridChange} />
						</div>
					</div>
				</div>
				{this.renderProcess()}
			</React.Fragment>
		)
	}
}

export default FilePage